<?php

/**
 * 前台首页控制器
 */
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

//use Illuminate\Support\Facades\DB;
use App\Models;

class HomeController extends Controller
{
    public function index(){
		$tdk['title'] = '编程语言学习和Web开发教程 | 个人经历和互联网事件分享 - 代码示例网';
		$tdk['keywords'] = '编程语言学习，Web开发教程，个人经历分享，互联网事件，技术分享';
		$tdk['description'] = '代码示例网提供编程语言学习和Web开发教程，同时分享个人经历和互联网事件的见解和观点。';
		$fronts['tdk'] = $tdk;

		$fronts['user'] = Auth::user();
		//'art_id','title','content','cat_id','view','comm'
		$fronts['latestarts'] = Models\Art::select('art_id','title','created_at')->orderByDesc('created_at')->where([['is_state', '=', '0'],['is_del', '=', '1']])->limit(10)->get()->toArray();

		//热点缓存
		if (!Cache()->has('hotarts')) {
			$hotarts = Models\Art::select('art_id','title')->orderByDesc('view')->where([['is_state', '=', '0'],['is_del', '=', '1']])->limit(5)->get()->toArray();
			Cache()->set('hotarts',$hotarts,3600);
		}
		$fronts['hotarts'] = Cache()->get('hotarts');
		
		//各分类下取5条数据
		/*$arts = Models\Cat::all();
		foreach($arts as &$v){
			$v->arts = $v->arts()->select('art_id','title','created_at')->where([['is_state', '=', '0'],['is_del', '=', '1']])->orderByDesc('created_at')->limit(10)->get()->toArray();
		}*/
		$arts = Models\Cat::with(['arts' => function ($query) {
			$query->limit(0); //不加载关联表，免的内存溢出
		}])->get();
		foreach ($arts as $v) {
			$v->arts = $v->arts()->select('art_id','title','created_at')->where([['is_state', '=', '0'],['is_del', '=', '1']])->orderByDesc('created_at')->limit(10)->get()->toArray();
		}
		$fronts['arts'] = $arts;
		
		//评论
		$fronts['comments'] = Models\Comment::with(['art' => function ($query) {
			$query->select('art_id','title','created_at')->where([['is_state', '=', '0'],['is_del', '=', '1']]); 
		}])->select('comment_id','art_id','username','comment','zan','ip','created_at')->where([['status', '=', '1']])->orderByDesc('created_at')->limit(5)->get()->toArray();

		$fronts['tags'] = Models\Tag::select('tag_id','tagname')->orderByDesc('tag_id')->groupBy('tagname')->limit(21)->get()->toArray();
		
		//归档缓存 格式：2017年01月  , count(*) as num
		if (!Cache()->has('datearts')) {
			$datearts = Models\Art::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as time')
			->where([['is_state', '=', '0'],['is_del', '=', '1']])->orderByDesc('created_at')->groupBy('time')->limit(21)->get()->toArray();
			Cache()->set('datearts',$datearts,3610);
		}
		$fronts['datearts'] = Cache()->get('datearts');
		//删除缓存
		//Cache()->forget('datearts');
		
		//友链缓存
		if (!Cache()->has('links')) {
			$links = Models\Links::where('status',0)->orderByDesc('sby')->pluck('url','name');
			Cache()->set('links',$links,600);
		}
		$fronts['links'] = Cache()->get('links');

		//DB::connection()->enableQueryLog();  // 开启QueryLog
		//$categories = Models\Cat::with('arts')->get();
		//dump(DB::getQueryLog());
		
		
        return view('front/home/index',$fronts);
    }
	
	//分类页
	public function cates(Request $request,$keyboard=null){
		
		$fronts['catspy'] = array_column($this->cats,null,'pinyin')[$keyboard]??0;
		//=0该分类不存在,随机一个分类返回数据
		$fronts['cates'] = Models\Art::select('art_id','title')
			->where('cat_id',$fronts['catspy'] != 0?$fronts['catspy']['cat_id']:array_rand($this->cats))
			->where([['is_state', '=', '0'],['is_del', '=', '1']])
			->orderByDesc('created_at')->simplePaginate(30);
			
		$tdk['title'] = $fronts['catspy']['catname']??$keyboard .'_编程语言学习和Web开发教程 | 个人经历和互联网事件分享 - 代码示例网';
		$tdk['keywords'] = $fronts['catspy']['catname']??$keyboard .'，编程语言，Web开发教程，个人经历，互联网事件';
		$tdk['description'] = $fronts['catspy']['catname']??$keyboard .'，代码示例网提供编程语言学习和Web开发教程，同时分享个人经历和互联网事件的见解和观点。';
		$fronts['tdk'] = $tdk;
		
		$fronts['keyboard'] = $keyboard;
		
		//热点缓存
		if (!Cache()->has('hotarts')) {
			$fronts['hotarts'] = Models\Art::select('art_id','title')->orderByDesc('view')->where([['is_state', '=', '0'],['is_del', '=', '1']])->limit(5)->get()->toArray();
			Cache()->set('hotarts',$fronts['hotarts'],3600);
		}
		$fronts['hotarts'] = Cache()->get('hotarts');

		return view('front/home/cates',$fronts);
	}
	
	//搜索页
	public function search(Request $request,$keyboard=null){
		$tdk['title'] = $keyboard.'搜索结果_编程语言学习和Web开发教程 | 个人经历和互联网事件分享 - 代码示例网';
		$tdk['keywords'] = $keyboard.' 搜索结果';
		$tdk['description'] = $keyboard.'搜索结果，代码示例网提供编程语言学习和Web开发教程，同时分享个人经历和互联网事件的见解和观点。';
		$fronts['tdk'] = $tdk;
		
		$fronts['keyboard'] = $keyboard;
		$catid = $request->input('tbname');
		
		if($request->isMethod('post') || $request->is('search/*')){
			$latestarts = Models\Art::select('art_id','cat_id','title','content','created_at')
			->where('title', 'like', "{$keyboard}%")->where([['is_state', '=', '0'],['is_del', '=', '1']])
			->where(function ($query) use($catid) {
                if (isset($catid)) {//选择了分类
                    $query->where('cat_id', $catid);
                }
            })
			->orderByDesc('created_at')->paginate(10);
			
			//记录搜索的关键词
			Models\Searchhis::create([
                'cid' => $catid??0,
                'keywords' => $keyboard,
				'created_at' => date('Y-m-d H:i:s'),
            ]);

		}else {
			$latestarts = Models\Art::select('art_id','cat_id','title','content','created_at')->orderByDesc('created_at')->where([['is_state', '=', '0'],['is_del', '=', '1']])->paginate(10);
			
		}
		$fronts['latestarts'] = $latestarts;
		
		//热点缓存
		if (!Cache()->has('hotarts')) {
			$fronts['hotarts'] = Models\Art::select('art_id','title')->orderByDesc('view')->where([['is_state', '=', '0'],['is_del', '=', '1']])->limit(5)->get()->toArray();
			Cache()->set('hotarts',$fronts['hotarts'],3600);
		}
		$fronts['hotarts'] = Cache()->get('hotarts');
		
		return view('front/home/search',$fronts);
	}
	
	//归档
	public function dates(Request $request,$keyboard=null){
		
		$tdk['title'] = $keyboard.'文章归档_编程语言学习和Web开发教程 | 个人经历和互联网事件分享 - 代码示例网';
		$tdk['keywords'] = $keyboard .' 文章归档';
		$tdk['description'] = $keyboard.'文章归档，代码示例网提供编程语言学习和Web开发教程，同时分享个人经历和互联网事件的见解和观点。';
		$fronts['tdk'] = $tdk;
		
		$fronts['keyboard'] = $keyboard;
		
		if($keyboard){
			$fronts['dates'] = Models\Art::select('art_id','title')
			->whereRaw('DATE_FORMAT(created_at, "%Y-%m") = ?',[$keyboard])->where([['is_state', '=', '0'],['is_del', '=', '1']])
			->orderByDesc('created_at')->simplePaginate(30);

		} else {
			$d = Models\Art::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as time')
			->where([['is_state', '=', '0'],['is_del', '=', '1']])->orderByDesc('created_at')->groupBy('time')->get()->toArray();
			$dates = [];
			foreach($d as $v){
				$y = substr($v['time'],0,4);
				// 如果年份不存在于结果数组中，则创建一个新的空数组
				if (!isset($dates[$y])) {
					$dates[$y] = [];
				}
				// 将字符串添加到对应的年份数组中
				$dates[$y][] = $v;
			}
			$fronts['dates'] = $dates;
		}
		
		//热点缓存
		if (!Cache()->has('hotarts')) {
			$fronts['hotarts'] = Models\Art::select('art_id','title')->orderByDesc('view')->where([['is_state', '=', '0'],['is_del', '=', '1']])->limit(5)->get()->toArray();
			Cache()->set('hotarts',$fronts['hotarts'],3600);
		}
		$fronts['hotarts'] = Cache()->get('hotarts');
		
		return view('front/home/dates',$fronts);
	}
}
